package cn.lwx.javaweb.web.action;

import cn.lwx.javaweb.bean.User;
import cn.lwx.javaweb.utils.UserUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 免登录判断
 * @author lwx
 * @date 2022-05-26 代码重构
 */
@WebServlet("/avoid/login")
public class AvoidTheLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取cookie
        Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("username".equals(name)) {
                    username = cookie.getValue();
                } else if ("password".equals(name)) {
                    password = cookie.getValue();
                }
            }
        }

        // username和password不为空
        if (username != null && password != null) {
            // 判断用户是否有效--业务逻辑
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            boolean flag = UserUtils.isValid(user);

            if (flag) {
                // 用户有效，获取session，把账号密码信息存入session中
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
            }
        }
        // 跳index页面
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
}
